#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os.path
import os
import re

class RecursiveRename():
    def __init__(self,basepath):
        self.basepath=basepath
        self.globallist=list()
        pass

    def _processWithRecursive(self,basedir, idx):

        if os.path.isfile(basedir):
            self.globallist.pop()
            return
        sdirs = os.listdir(basedir)
        sdirs = list(filter(lambda dir: not re.match('\._.*', dir), sdirs))

        sdirs.sort()
        idx2=0
        for sdir in sdirs:

            filedir = os.path.join(basedir, sdir)

            if os.path.isdir(filedir):
                print(self.globallist);
                self.globallist.append(sdir)
                self._processWithRecursive(filedir, idx + 1)
            else:
                # 说明已经是文件了
                idx2+=1
                ns=''
                if re.match('_[\d]{2}.*', sdir):
                    continue
                if re.match('._[\d]{1,2}.*', sdir):
                    continue
                for namesuffix in self.globallist:
                    ns+=namesuffix

                print('\t' * idx, sdir,'-->', ns[1:],'-',sdir)
                #print(sdir.replace(ns[1:]+'-'+ns[1:],ns[1:]))
                #os.rename(os.path.join(basedir,sdir),os.path.join(basedir,sdir.replace(ns[1:]+'-'+ns[1:],ns[1:])))
                os.rename(os.path.join(basedir,sdir),os.path.join(basedir,ns[:]+'-'+sdir))

                #os.rename()
        self.globallist.pop()

    def process(self):
        # path='/Volumes/DOCUMENT/Baiduyun/24 项目架构与优化'
        dirs = os.listdir(path)
        dirs.sort()
        for dir in dirs:
            #if not re.match('\d{2}.*', dir):
            #    continue
            basedir = os.path.join(path, dir)
            self.globallist.append(dir)
            self._processWithRecursive(basedir, 0)




if __name__ == "__main__":
    path = '/Volumes/TOOLS/28 Angular5'
    #dirs=os.listdir(path)
    #dirs.sort();
    #for dir in dirs:
    #    print(dir)
    RecursiveRename(path).process()



